package com.thread.Demo01;

//多线程下载网图

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class TestThread2 implements Runnable{
    private String url;
    private String name;//保存的文件名

    //构造方法
    public TestThread2(String url,String name){
        this.url = url;
        this.name = name;

    }

    //下载图片线程的执行体
    @Override
    public void run() {
        ImgDownloader imgDownloader = new ImgDownloader();
        imgDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    //主线程
    public static void main(String[] args) {
            TestThread2 t1 = new TestThread2("https://store.hituyu.com/LqiGjDyCFyeQfqRyPYcnMaqJpIMtxsFK..png","1.jpg");
            TestThread2 t2  = new TestThread2("https://store.hituyu.com/CqKCCwCkJhtBCnUoEUeBuGvUsqPWkZMC..png","2.jpg");
            TestThread2 t3 = new TestThread2("https://store.hituyu.com/GgCPAtESyYKBXTgYxjBvuimKDUlqEcte..png","3.jpg");
            new Thread(t1).start();
            new Thread(t2).start();
            new Thread(t3).start();
            /*
            理想是1,2,3
            但事实是:
            下载了文件名为:3.jpg
            下载了文件名为:2.jpg
            下载了文件名为:1.jpg
            */
    }
}
class ImgDownloader{
    //下载方法
    public void downloader(String url,String name){
        //使用文件工具类
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader wrong");
        }
    }
}
    